var package = require('./package.json');
var gulp = require('gulp');
var nui = require('gulp-nui');
var replace = require('gulp-replace');
var htmlmin = require('gulp-htmlmin');
var path = require('path');

//静态资源根目录
var staticUrl = path.join(__dirname, './src/');
//公共库资源目录
var staticLibs = path.join(__dirname, '../libs/');
//配置文件地址
var configurl = path.join(__dirname, './src/config.js');

//nui自动化参数
var options = {
	base:path.join(__dirname, '../'),
	url:configurl,
	ignore:['util', 'template', 'component', 'events', 'highcharts'],
	jsmin:{
		//validate.js 中的“$”符号混淆压缩之后，在IE中会报错。。。 fuck!
		mangle:{
			except:['$']
		} 
	}
}

//修改页面静态资源版本号，以及合并压缩模块
var pagerev = function(type){
	if(!type){
		delete options.mintype
	}
	else{
		options.mintype = type
	}
	gulp.src(['./html/**/*.html'])
		.pipe(nui(options))
		.pipe(gulp.dest('./html/'))
}

gulp.task('pagerev', function(){
	delete options.compress;
	pagerev()
})

//修改js模块中资源版本号
gulp.task('jsrev', function(){
	gulp.src([staticUrl+'**/*.js', '!'+ staticUrl +'**/*-min.js', '!'+configurl])
	     .pipe(nui({
			 filterPath:function(src){
				return src.replace('<%staticLibs%>', staticLibs).replace('<%staticUrl%>', staticUrl)
			 }
		 }))
	     .pipe(gulp.dest(staticUrl))
})

//修改业务模块css中资源版本号
gulp.task('cssrev', function(){
	gulp.src([staticUrl+'**/*.{css,less}', '!'+ staticUrl +'**/*{-min}.css'])
	     .pipe(nui())
	     .pipe(gulp.dest(staticUrl))
})

//修改公共库css中的资源版本号
gulp.task('libsCssrev', function(){
	gulp.src([staticLibs+'**/*.{css,less}', '!'+ staticLibs +'**/*{-min}.css'])
	     .pipe(nui())
	     .pipe(gulp.dest(staticLibs))
})

//替换html路径
gulp.task('replace', function(){
    gulp.src(['./html/**/*.html'])
    .pipe(replace(/(src|href)="([^"]+)"/g, function(a, b, c){
        return b + '="' + c.replace(/^(.+\/(libs|easyAbacus\/))/, package.staticUrl + '$2') + '"'
    }))
    .pipe(replace(/(<script type="text\/javascript">)(<\/script>)/, '$1var basePath="'+ package.basePath +'",staticUrl="'+ package.staticUrl +'",serviceUrl="'+ package.serviceUrl +'"$2'))
    .pipe(htmlmin({
        collapseWhitespace:true,
        removeComments:true,
        removeEmptyAttributes:true
    }))
    .pipe(gulp.dest('./dist/'))
})

gulp.task('watch', function(){
    
    if(package.environment === 'dev'){
        gulp.watch([
            staticUrl+'**/*.js', 
            staticLibs+'**/*.js', 
            '!'+staticUrl+'**/*-min.js',
            '!'+configurl
        ], function(event){
            pagerev('js');
            console.log('File ' + event.path + ' was ' + event.type + new Date());
        });

        gulp.watch([
            staticUrl+'**/*.{css,less}', 
            staticLibs+'**/*.{css,less}', 
            '!'+staticUrl+'**/*-min.css',
        ], function(event){
            pagerev('css');
            console.log('File ' + event.path + ' was ' + event.type + new Date());
        });

        var pic = '{jpg,png,gif,eot,svg,ttf,woff}';

        gulp.watch([staticUrl+'**/*.'+pic, staticLibs+'**/*.'+pic], ['jsrev']);

        gulp.watch([staticUrl+'**/*.'+pic], ['cssrev']);
        
        gulp.watch([staticLibs+'**/*.'+pic], ['libsCssrev']);

    }

    gulp.watch(['html/*.html'], ['replace']);
});

if(package.environment === 'dev'){
    gulp.task('default', ['pagerev', 'jsrev', 'cssrev', 'libsCssrev', 'replace', 'watch']);
}
else{
    gulp.task('default', ['replace', 'watch']);
}